<?php

namespace ff\database\mysql;

use ff\database\DbException;

class mysqli
{
    public $curconfkey;
    public $tablepre;
    public $version = '';
    public $drivertype = 'mysqli';
    public $querynum = 0;
    public $slaveid = 0;
    public $curlink;
    public $link = array();
    public $config = array();
    public $sqldebug = array();
    public $map = array();

    public function db_mysql($config = array())
    {
        if (!empty($config)) {
            $this->set_config($config);
        }
    }

    public function set_config($config)
    {
        $this->config = &$config;
    }

    public function connect($confkey = '')
    {

        if (empty($this->config) || empty($this->config[$confkey])) {
            $this->halt('config_db_not_found');
        }

        if (!isset($this->link[$confkey])) {
            $this->link[$confkey] = $this->_dbconnect(
                $this->config[$confkey]['dbhost'],
                $this->config[$confkey]['dbuser'],
                $this->config[$confkey]['dbpw'],
                $this->config[$confkey]['dbcharset'],
                $this->config[$confkey]['dbname'],
                $this->config[$confkey]['pconnect']
            );
        }

        $this->curconfkey = $confkey;
        $this->tablepre[$confkey] = $this->config[$confkey]['tablepre'];
        $this->curlink = $this->link[$confkey];

    }

    public function _dbconnect($dbhost, $dbuser, $dbpw, $dbcharset, $dbname, $pconnect, $halt = true)
    {

        $link = new \mysqli();
        if (!$link->real_connect($dbhost, $dbuser, $dbpw, $dbname, null, null, MYSQLI_CLIENT_COMPRESS)) {
            $halt && $this->halt('notconnect', $this->errno());
        } else {
            $this->curlink = $link;
            if ($this->version() > '4.1') {
                $link->set_charset($dbcharset ? $dbcharset : $this->config[1]['dbcharset']);
                $serverset = $this->version() > '5.0.1' ? 'sql_mode=\'\',' : '';
                $serverset .= 'character_set_client=binary';
                $serverset && $link->query("SET $serverset");
            }
        }
        return $link;
    }

    public function table_name($tablename)
    {
        if (!empty($this->map) && !empty($this->map[$tablename])) {
            $id = $this->map[$tablename];
            if (!$this->link[$id]) {
                $this->connect($id);
            }
            $this->curlink = $this->link[$id];
        } else {
            $this->curlink = $this->link[$this->curconfkey];
        }
        return $this->tablepre[$this->curconfkey] . $tablename;
    }

    public function select_db($dbname)
    {
        return $this->curlink->select_db($dbname);
    }

    public function fetch_array($query, $result_type = MYSQLI_ASSOC)
    {
        if ($result_type == 'MYSQL_ASSOC') {
            $result_type = MYSQLI_ASSOC;
        }

        return $query ? $query->fetch_array($result_type) : null;
    }

    public function fetch_first($sql)
    {
        return $this->fetch_array($this->query($sql));
    }

    public function result_first($sql)
    {
        return $this->result($this->query($sql), 0);
    }

    public function query($sql, $silent = false, $unbuffered = false)
    {
        if (defined('API_DEBUG') && API_DEBUG) {
            $starttime = microtime(true);
        }

        if ('UNBUFFERED' === $silent) {
            $silent = false;
            $unbuffered = true;
        } elseif ('SILENT' === $silent) {
            $silent = true;
            $unbuffered = false;
        }

        $resultmode = $unbuffered ? MYSQLI_USE_RESULT : MYSQLI_STORE_RESULT;

        if (!($query = $this->curlink->query($sql, $resultmode))) {
            if (in_array($this->errno(), array(2006, 2013)) && substr($silent, 0, 5) != 'RETRY') {
                $this->connect();
                return $this->curlink->query($sql, 'RETRY' . $silent);
            }
            if (!$silent) {
                $this->halt($this->error(), $this->errno(), $sql);
            }
        }

        if (defined('API_DEBUG') && API_DEBUG) {
            $this->sqldebug[] = array($sql, number_format((microtime(true) - $starttime), 6), debug_backtrace(), $this->curlink);
        }

        $this->querynum++;
        return $query;
    }

    public function affected_rows()
    {
        return $this->curlink->affected_rows;
    }

    public function error()
    {
        return (($this->curlink) ? $this->curlink->error : mysqli_error());
    }

    public function errno()
    {
        return intval(($this->curlink) ? $this->curlink->errno : mysqli_errno());
    }

    public function result($query, $row = 0)
    {
        if (!$query || $query->num_rows == 0) {
            return null;
        }
        $query->data_seek($row);
        $assocs = $query->fetch_row();
        return $assocs[0];
    }

    public function num_rows($query)
    {
        $query = $query ? $query->num_rows : 0;
        return $query;
    }

    public function num_fields($query)
    {
        return $query ? $query->field_count : null;
    }

    public function free_result($query)
    {
        return $query ? $query->free() : false;
    }

    public function insert_id()
    {
        return ($id = $this->curlink->insert_id) >= 0 ? $id : $this->result($this->query("SELECT last_insert_id()"), 0);
    }

    public function fetch_row($query)
    {
        $query = $query ? $query->fetch_row() : null;
        return $query;
    }

    public function fetch_fields($query)
    {
        return $query ? $query->fetch_field() : null;
    }

    public function version()
    {
        if (empty($this->version)) {
            $this->version = $this->curlink->server_info;
        }
        return $this->version;
    }

    public function escape_string($str)
    {
        return $this->curlink->escape_string($str);
    }

    public function close()
    {
        return $this->curlink->close();
    }

    public function halt($message = '', $code = 0, $sql = '')
    {
        throw new DbException($message, $code,$sql);
    }

}
